load("//rust:defs.bzl", "rust_binary", "rust_clippy", "rust_library")
load("//tools:tool_utils.bzl", "aspect_repository")

exports_files(
    [
        "rustfmt.toml",
        "rustfmt_utils.bzl",
    ],
    visibility = ["//visibility:public"],
)

rust_library(
    name = "rustfmt_lib",
    srcs = glob(
        include = ["src/**/*.rs"],
        exclude = [
            "src/**/*main.rs",
            "src/bin/**",
        ],
    ),
    data = [
        "//:rustfmt.toml",
        "//rust/toolchain:current_rustfmt_toolchain_for_target",
    ],
    edition = "2018",
    rustc_env = {
        "RUSTFMT": "$(rlocationpath //rust/toolchain:current_rustfmt_toolchain_for_target)",
        "RUSTFMT_CONFIG": "$(rlocationpath //:rustfmt.toml)",
    },
    deps = [
        "//tools/runfiles",
    ],
)

# Deprecated but present for compatibility.
alias(
    name = "rustfmt",
    actual = ":target_aware_rustfmt",
    deprecation = "Prefer //tools/upstream_wrapper:rustfmt",
    visibility = ["//visibility:public"],
)

# This is a wrapper around the upstream rustfmt binary which is aware of targets,
# and will try to do things like set the correct edition for files when formatting them based on their owning targets.
rust_binary(
    name = "target_aware_rustfmt",
    srcs = [
        "src/main.rs",
    ],
    data = [
        "//:rustfmt.toml",
    ],
    edition = "2018",
    rustc_env = {
        "ASPECT_REPOSITORY": aspect_repository(),
        "RUST_DEFAULT_EDITION": "$(RUST_DEFAULT_EDITION)",
    },
    toolchains = ["@rules_rust//rust/toolchain:current_rust_toolchain"],
    visibility = ["//visibility:public"],
    deps = [
        ":rustfmt_lib",
        "//util/label",
    ],
)

rust_binary(
    name = "rustfmt_test",
    srcs = [
        "src/bin/test_main.rs",
    ],
    edition = "2018",
    visibility = ["//visibility:public"],
    deps = [
        ":rustfmt_lib",
        "//tools/runfiles",
    ],
)

rust_clippy(
    name = "rustfmt_clippy",
    testonly = True,
    visibility = ["//visibility:private"],
    deps = [
        ":target_aware_rustfmt",
    ],
)

# Deprecated but present for compatibility.
alias(
    name = "upstream_rustfmt",
    actual = "//tools/upstream_wrapper:rustfmt",
    deprecation = "Prefer //tools/upstream_wrapper:rustfmt",
    visibility = ["//visibility:public"],
)
